const router = require('@koa/router')()
const jwt = require('../utils/jwt')
const { findNoteListByType,addNote } = require('../controllers/index')
const { formateTime } = require('../utils/formateTime')

router.get('/findNoteListByType',jwt.verify(),async (ctx)=>{
    // 检验token合理再去数据库中查找数据返回给前端
    const { note_type } = ctx.request.query
    const res = await findNoteListByType(note_type,ctx.userId)
    try {
        if(res.length){
            ctx.body = {
                code: '800',
                data:res,
                msg:'查询成功'
            }
        }else{
            ctx.body = {
                code: '801',
                msg:'查询失败'
            }
        }
    } catch (error) {
        ctx.body = {
            code: '802',
            msg:'服务器异常',
            data: error
        }
    }
})

router.post('/note-publish',jwt.verify(),async (ctx)=>{
    const { title,note_content,note_type,head_img } = ctx.request.body

    const c_time = formateTime(new Date())
    const m_time = formateTime(new Date())
    console.log(c_time);
    try {
        console.log(32321321);
        const values = {
            title,
            note_content,
            note_type,
            head_img,
            c_time,
            m_time,
            userId:ctx.userId,
            nickname:ctx.nickname
        }
        console.log(values);
        const res = await addNote(values)
        console.log(res.affectedRows);
        if(res.affectedRows){
            ctx.body = {
                code: '800',
                data:'success',
                msg: '发布成功'
            }
        }else{
            ctx.body = {
                code: '801',
                msg:'发布失败'
            }
        }
    } catch (error) {
        ctx.body = {
            code: '802',
            msg:'服务器异常',
            data: error
        }
    }
})

module.exports = router